<template>
  <view>
    <view class="whole">
      <image mode="widthFix" src="../../static/logo.png"></image>
      <button class="name" @click="doLogin" :loading="btnLoading">登录</button>
      <!-- 授权手机号弹窗 -->
      <uni-popup ref="popup" type="center" :animation="false" :mask-click="false">
        <view class="content-view">
          <uni-card :border="false">
            <view class="popup-info">
              <view class="popup-title">绑定手机号</view>
              <view class="popup-content">请先绑定手机号再进行此操作</view>
              <button class="popup-button" type="default" open-type="getPhoneNumber" @getphonenumber="getphoneNumber"
                :loading="phoneBtnLoading">绑定手机号</button>
            </view>
          </uni-card>
        </view>
      </uni-popup>
    </view>
  </view>
</template>

<script>
  import {
    mapActions
  } from 'vuex';
  import {
    login,
    precheck
  } from '@/api/login.js';
  import {
    debounce,
    goPage
  } from '@/common/main.js';
  export default {
    data() {
      return {
        username: {
          name: ''
        },
        avatar: '',
        wechatInfo: {},
        code: '',
        code2: '',
        btnLoading: false, //按钮loading
        phoneBtnLoading: false,
        checkDetail: {},
      }
    },
    methods: {
      ...mapActions(['Login']),
      // 登录
      doLogin() {
        uni.login({
          provider: 'weixin',
          success: succ => {
            this.code = succ.code;
            this.getUserInfos();
          },
          complete: comt => {}
        });


      },
      doCheck() {
        precheck(`/login?code=${this.code}`, 'post').then(res => {
          this.checkDetail = res.data ? res.data : {};
          if (res.data && res.data.token) { //有手机号，直接登录
            this.$Toast.success('登录成功');
            uni.setStorage({
              key: 'phone',
              data: res.data.username
            });
            uni.setStorageSync('token', res.data.token);
            goPage();
          } else { //无用户信息或无手机号
            this.$refs.popup.open('center');
          }
        });
      },
      // 绑定手机号
      doBinding(data) {
        precheck('/binding', 'post', {
          "code": this.code2,
          "encryptedData": data.encryptedData,
          "iv": data.iv,
          "openId": this.checkDetail.openId,
        }).then(res => {
          this.phoneBtnLoading = false;
          if (res.code == 200) {
            this.$Toast.success('登录成功');
            uni.setStorage({
              key: 'phone',
              data: res.data.phoneNum
            });
            uni.setStorageSync('token', res.data.token);
            goPage();
          }
        }).catch(err => {
          this.phoneBtnLoading = false;
        })
      },

      getUserInfos() {
        this.btnLoading = true;
        let that = this;
        uni.showModal({
          title: '温馨提示',
          content: '亲，授权微信登录后才能正常使用小程序功能',
          success(res) {
            //如果用户点击了确定按钮
            if (res.confirm) {
              uni.getUserProfile({
                provider: 'weixin',
                desc: '登录',
                success: (res) => {
                  that.$store.commit('setwxuserinfo', res.userInfo)

                  that.wechatInfo = res;

                  uni.login({
                    provider: 'weixin',
                    success: succ => {
                      that.code2 = succ.code;
                      that.doCheck();
                    },
                    complete: comt => {}
                  });

                },
                fail: (res) => {
                  //拒绝授权
                  that.btnLoading = false;
                  that.$Toast.none('您拒绝了请求,不能正常使用小程序');
                  return;
                },
              })
            } else if (res.cancel) {
              //如果用户点击了取消按钮
              that.btnLoading = false;
              that.$Toast.none('您拒绝了请求,不能正常使用小程序');
              return;
            }
          }
        });
      },
      // 获取手机号
      getphoneNumber(e) {
        this.phoneBtnLoading = true;

        this.$Toast.loading('手机号获取中');
        let res = e.detail;
        if (res.encryptedData) {
          let params = {
            "code": this.code2,
            "encryptedData": res.encryptedData,
            "iv": res.iv,
            "rawData": this.wechatInfo.rawData,
            "signature": this.wechatInfo.signature
          }

          if (!this.checkDetail || Object.keys(this.checkDetail).length == 0) { //无用户信息
            this.regLogin(params);
          } else if (!this.checkDetail.token) {
            this.doBinding(res);
          }
        } else {
          this.phoneBtnLoading = false;
          uni.showToast({
            title: '登录失败！',
            icon: 'error',
            duration: 1500
          })
          this.$refs.popup.close();
        }
      },
      regLogin(params) {
        login('', 'post', params).then(res => {
            this.$Toast.loading('登录中···');
            this.phoneBtnLoading = false;
            if (res.code == 200) {
              this.$Toast.success('登录成功');
              uni.setStorage({
                key: 'phone',
                data: res.data.phoneNum
              });
              uni.setStorageSync('token', res.data.token);
              goPage();
            } else {
              this.$refs.popup.close();
            }
          })
          .finally(final => {
            this.phoneBtnLoading = false;
          })
          .catch(err => {
            console.log(err)
            this.phoneBtnLoading = false;
            this.$refs.popup.close();
          })
      },
      info() {
        let that = this;
        uni.getStorage({
          key: 'userinfo',
          success(res) {
            that.username.name = JSON.parse(res.data).nickName;
            that.avatar = JSON.parse(res.data).avatarUrl;
          }
        })
      }
    }
  }
</script>

<style lang="less">
  page {
    background-color: #fff;
  }

  .whole {
    width: 100%;
    margin-top: 50%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    image {
      width: 260upx;
      height: 260upx;
      margin-bottom: 30%;
    }
  }

  .name {
    width: 90%;
    background-color: #4ea7ff;
    height: 100upx;
    line-height: 100upx;
    font-weight: normal;
    color: #fff;
    font-size: 28upx;
  }

  .popup-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 15upx 25upx;

    .popup-title {
      font-size: 30upx;
      font-weight: bold;
    }

    .popup-content {
      font-size: 26upx;
      color: #bdbdbd;
      padding: 20upx 0;
    }

    .popup-button {
      width: 100%;
      background-color: #4ea7ff;
      height: 70upx;
      line-height: 70upx;
      font-weight: normal;
      color: #fff;
      font-size: 28upx;
    }
  }

  button::after {
    border: none;
  }
</style>